//
//  SEYYTextLinePositionModifier.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/9.
//

import UIKit
import YYText

private let ascentScale: CGFloat = 0.84
private let descentScale: CGFloat = 0.16

class SEYYTextLinePositionModifier: NSObject, YYTextLinePositionModifier {
    var font: UIFont
    
    private var paddingTop: CGFloat = 2 // 文本顶部留白
    private var paddingBottom: CGFloat = 2 // 文本底部留白
    private var lineHeightMultiple: CGFloat // 行距倍数
    
    required init(font: UIFont) {
        self.lineHeightMultiple = 1.23
        self.font = font
        super.init()
    }
    
    // MARK: - YYTextLinePositionModifier
    
    func modifyLines(_ lines: [YYTextLine], fromText text: NSAttributedString, in container: YYTextContainer) {
        let ascent = font.pointSize * ascentScale
        let lineHeight = font.pointSize * lineHeightMultiple
        for line in lines {
            var position = line.position
            position.y = paddingTop + ascent + CGFloat(line.row) * lineHeight
            line.position = position
        }
    }
    
    func copy(with zone: NSZone? = nil) -> Any {
        let one = type(of: self).init(font: font)
        return one
    }
    
    func heightForLineCount(_ lineCount: Int) -> CGFloat {
        if lineCount == 0 { return 0 }
        
        let ascent = font.pointSize * ascentScale
        let descent = font.pointSize * descentScale
        let lineHeight = font.pointSize * lineHeightMultiple
        return paddingTop + paddingBottom + ascent + descent + CGFloat(lineCount - 1) * lineHeight
    }
}
